<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas</title>
  <link rel="stylesheet" href="./style.css">
</head>

<body>
  <canvas id="canvas"></canvas>
  <script>
    let canvas = document.getElementById("canvas");
    canvas.width = document.documentElement.clientWidth
    canvas.height = document.documentElement.clientHeight
    let ctx = canvas.getContext("2d");
    ctx.fillStyle = "rgb(200,0,0)";
    ctx.lineWidth = 6
    ctx.lineCap = 'round'
    let painting = false
    let last = null

    function drawLine(x1, y1, x2, y2) {
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.stroke();
    }


    //手机端
    let isTouchDevice = 'ontouchstart' in
      document.documentElement
    // console.log(isTouchDevice);
    if (isTouchDevice) {
      canvas.ontouchstart = function (e) {
        let x = e.touches[0].clientX
        let y = e.touches[0].clientY
        last = [x, y]
      }
      canvas.ontouchmove = function (e) {
        let x = e.touches[0].clientX
        let y = e.touches[0].clientY
        // ctx.beginPath();
        // ctx.arc(x, y, 10, 0, 2 * Math.PI, false);
        // ctx.fill();
        drawLine(last[0], last[1], x, y)
        last = [x, y]
      }
    }
    //PC端
    canvas.onmousedown = function (e) {
      painting = true
      last = [e.clientX, e.clientY]
    }
    canvas.onmousemove = function (e) {
      if (painting) {
        // 点
        // ctx.fillRect(e.clientX - 5, e.clientY - 5, 10, 10);
        // 圆
        // ctx.beginPath();
        // ctx.arc(e.clientX, e.clientY, 10, 0, 2 * Math.PI, false);
        // ctx.fill();


        drawLine(last[0], last[1], e.clientX, e.clientY)
        last = [e.clientX, e.clientY]
      }
    }

    canvas.onmouseup = function () {
      painting = false
    }
  </script>
</body>

</html>